package com.neutech.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/b")
public class BookServlet extends HttpServlet {

    private static final List<Book> books = new ArrayList<>();

    public static class Book {
        String title;
        String author;
        String isbn;
        public Book(String title, String author, String isbn) {
            this.title = title;
            this.author = author;
            this.isbn = isbn;
        }
        @Override
        public String toString() {
            return "Book{" +
                    "标题='" + title + '\'' +
                    ", 作者='" + author + '\'' +
                    ", isbn='" + isbn + '\'' +
                    '}';
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        String path = request.getPathInfo();
        System.out.println(path);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        String path = request.getPathInfo();
        System.out.println(path);
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String isbn = request.getParameter("isbn");
        if ("/addBook".equals(path)) {
            boolean added = false;
            for (Book book : books) {
                if (book.isbn.equals(isbn)) {
                    response.getWriter().println("ISBN已存在");
                    return;
                }
            }
            books.add(new Book(title, author, isbn));
            response.getWriter().println("添加成功: " + new Book(title, author,
                    isbn));
        } else if ("/deleteBook".equals(path)) {
            books.removeIf(book -> book.isbn.equals(isbn));
            response.getWriter().println("删除成功");
        } else {

        }
        String query = request.getParameter("query");
        if ("/searchBook".equals(path)) {
            List<Book> results = new ArrayList<>();
            for (Book book : books) {
                if (book.title.contains(query) || book.isbn.equals(query)) {
                    results.add(book);
                }
            }
            if (results.isEmpty()) {
                response.getWriter().println("未找到图书");
            } else {
                for (Book book : results) {
                    response.getWriter().println(book);
                }
            }
        } else {

        }
    }
}

